<?php
/**
 * Created by PhpStorm.
 * User: yajunyu
 * Date: 2018/12/21
 * Time: 11:34
 */

namespace app\admin\controller;


use app\admin\model\UpmsUser;
use app\common\base\BaseController;
use app\common\utils\ReturnCode;
use think\helper\hash\Md5;


/**
 * @title 登录注册
 * Class Login
 */
class Login extends BaseController
{
    //统一错误防止黑客猜密码
    private $errorMsg = '手机号或者密码错误！';


    public function index()
    {
        echo openssl_random_pseudo_bytes(32);
    }

    /**
     * @title 用户登录API
     * @url admin/login/login
     * @method POST
     * @param string phone 手机号 空 必须
     * @param string password 密码 空 必须
     * @code 1 成功
     * @code 2 失败
     * @return int code 状态码（具体参见状态码说明）
     * @return string token token
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $this->requestType('POST');
        $userName = $this->request->param('userName');
        $password = $this->request->param('password');
        if (isPhone($userName)) {
            $userInfo = UpmsUser::get(['phone' => $userName]);
        } else {
            $userInfo = UpmsUser::get(['username' => $userName]);
        }

        $md5 = new Md5();
        if (!empty($userInfo)) {
            $md5->setSalt($userInfo['salt']);
            if ($userInfo['locked']) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '账号已经锁定');
            }
            if ($md5->check($password, $userInfo['password'])) {
                unset($userInfo['password']);
                unset($userInfo['salt']);
                $token = $md5->make(openssl_random_pseudo_bytes(32));
                cache($token, json_encode($userInfo), config('CACHE_TIME'));
                return $this->buildSuccess(['token' => $token], '登录成功', ReturnCode::SUCCESS);
            }
        }
        return $this->buildFailed(ReturnCode::LOGIN_ERROR, $this->errorMsg);
    }

    /**
     * @return array
     * 退出登录
     */
    public function loginOut()
    {
        $token = $this->request->header('token');
        cache($token, '');
        return $this->buildSuccess([]);
    }

}